import axios from 'axios/index'
import global from './global.js'
import env from './env.js'
import Cookie from "js-cookie"
import {Message} from 'iview'

const service = axios.create({
  baseURL: env.development_url,
  timeout: 5000,
  headers:{
    'Content-Type': 'application/json; charset=UTF-8'
  },
});

service.interceptors.request.use(config => {
  // 判断本地是否存在token，如果存在则带上请求头
  let token = Cookie.get(global.tokenTag);
  if (token) {
    config.headers = {
      'content-type': 'application/json',
      'x-auth-token': token	// 这里是token(可自行修改)
    };
  }
  return config
},error => {
  return Promise.reject(error);
});

window.doTimes = 0; //系统级别执行次数
service.interceptors.response.use(response => {
  const res = response.data;
  if(res.code === 10001 || res.code === 100002 || res.code===100003) {
    let routerPath =  window.location.pathname;
    if(window.doTimes>0) return;
    let countdown = 5;
    window.doTimes++;
    let timer = setInterval(() => {
      if(window.doTimes > countdown) {
        Cookie.remove(global.tokenTag);
        window.location.href='/login?fromUrl='+routerPath;
        clearInterval(timer)
      }else{
        Message.error("您的账号在其他设备上登录;系统将在"+countdown+"秒后返回系统登录页面");
        countdown--;
      }
    },1000);
  }else if(res.code === 100004) {
    window.doTimes++;
  }
  return response;
}, error => {
  console.log('err:' + error); // for debug
  return Promise.reject(error);
});

export default service
